package com.bwie.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.bwie.common.pojo.User;
import com.bwie.user.service.UserService;
import com.bwie.common.result.ApiResponse;
import com.bwie.common.exception.BusinessException;
import com.bwie.common.result.ErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 创建用户
     */
    @PostMapping
    public ApiResponse<Boolean> save(@RequestBody User user) {
        return ApiResponse.success(userService.save(user));
    }

    /**
     * 更新用户
     */
    @PutMapping
    public ApiResponse<Boolean> update(@RequestBody User user) {
        if (user.getId() == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR.getCode(), "用户ID不能为空");
        }
        return ApiResponse.success(userService.updateById(user));
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Boolean> delete(@PathVariable Long id) {
        User user = userService.getById(id);
        if (user == null) {
            throw new BusinessException(ErrorCode.USER_NOT_FOUND);
        }
        return ApiResponse.success(userService.removeById(id));
    }

    /**
     * 根据ID查询用户
     */
    @GetMapping("/{id}")
    public ApiResponse<User> getById(@PathVariable Long id) {
        User user = userService.getById(id);
        if (user == null) {
            throw new BusinessException(ErrorCode.USER_NOT_FOUND);
        }
        return ApiResponse.success(user);
    }

    /**
     * 查询所有用户
     */
    @GetMapping
    public ApiResponse<List<User>> getAll() {
        return ApiResponse.success(userService.list());
    }

    /**
     * 分页查询状态正常的用户
     */
    @GetMapping("/page")
    public ApiResponse<Page<User>> getPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        if (pageNum == null || pageSize == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR.getCode(), "页码和每页条数不能为空");
        }
        Page<User> page = new Page<>(pageNum, pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        return ApiResponse.success(userService.page(page, queryWrapper));
    }
}